package com.mission.schedule.activity

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.res.AssetFileDescriptor
import android.graphics.Bitmap
import android.media.MediaPlayer
import android.os.Bundle
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Html
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.android.volley.AuthFailureError
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.lcf.refreshlibrary.PullToRefreshBase
import com.lidroid.xutils.HttpUtils
import com.lidroid.xutils.exception.HttpException
import com.lidroid.xutils.http.RequestParams
import com.lidroid.xutils.http.ResponseInfo
import com.lidroid.xutils.http.callback.RequestCallBack
import com.lidroid.xutils.http.client.HttpRequest
import com.mission.schedule.R
import com.mission.schedule.applcation.App
import com.mission.schedule.bean.DownNewSixTaskBean
import com.mission.schedule.bean.TaskSynBean
import com.mission.schedule.bean.UserFrendsTask
import com.mission.schedule.constants.ShareFile
import com.mission.schedule.constants.URLConstants
import com.mission.schedule.utils.*
import com.mission.schedule.widget.SwipeLinearLayout
import com.nostra13.universalimageloader.core.DisplayImageOptions
import com.nostra13.universalimageloader.core.ImageLoader
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener
import kotlinx.android.synthetic.main.activity_new_friend_send_data.*
import kotlinx.android.synthetic.main.adapter_send_repeat_item.view.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.*
import kotlin.collections.ArrayList

class NewFriendSendDataActivity : Activity() {

    var pimage = ""
    var pname = ""

    var userid = ""
    var username = ""
    var puid = 0

    lateinit var share: SharedPrefUtil
    lateinit var context: Context
    lateinit var imageLoader: ImageLoader
    lateinit var animateFirstListener: ImageLoadingListener
    lateinit var options: DisplayImageOptions
    var adapter = ChildAdapter()
    private var dowmTime = ""
    var list = arrayListOf<UserFrendsTask>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_new_friend_send_data)

        context = this@NewFriendSendDataActivity
        imageLoader = ImageLoader.getInstance()
        animateFirstListener = AnimateFirstDisplayListener()

        share = SharedPrefUtil(context, ShareFile.USERFILE)

        userid = share.getString(ShareFile.USERID, "")
        username = share.getString(ShareFile.USERNAME, "")
        dowmTime = share.getString(ShareFile.DOWNTASKTIME, "2017-12-20 00:00:00")

        pname = intent.getStringExtra("pname")
        puid = intent.getIntExtra("puid", 0)
        pimage = intent.getStringExtra("pimage")

        recyclerview.layoutManager = LinearLayoutManager(context)
        recyclerview.adapter = adapter

        options = DisplayImageOptions.Builder()
                .showStubImage(R.mipmap.b1)
                .showImageForEmptyUri(R.mipmap.b1)
                .showImageOnFail(R.mipmap.b1).cacheInMemory(true)
                .cacheOnDisc(true).cacheInMemory(true)
                .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
                .build()


        setInit()

        top_ll_back.setOnClickListener {
            onBackPressed()
        }

        add.setOnClickListener {
            addDaile()
        }

        pull_refresh_scrollview.setOnRefreshListener(object : PullToRefreshBase.OnRefreshListener2<ScrollView> {


            override fun onPullDownToRefresh(
                    refreshView: PullToRefreshBase<ScrollView>) {
                loadData()
            }

            override fun onPullUpToRefresh(
                    refreshView: PullToRefreshBase<ScrollView>) {
                pull_refresh_scrollview.onRefreshComplete()
            }
        })

    }

    override fun onResume() {
        super.onResume()
        getData()
        adapter.notifyDataSetChanged()
        loadData()
    }

    private fun getData() {
        list.clear()
        list.addAll(App.getDBcApplication().getAllSendRepeatNoteData(userid, puid, 1,false) as ArrayList<UserFrendsTask>)
        list.addAll(App.getDBcApplication().getAllSendRepeatNoteData(userid, puid, 5,false) as ArrayList<UserFrendsTask>)
        list.addAll(App.getDBcApplication().getAllSendRepeatNoteData(userid, puid, 2,false) as ArrayList<UserFrendsTask>)
        list.addAll(App.getDBcApplication().getAllSendRepeatNoteData(userid, puid, 3,false) as ArrayList<UserFrendsTask>)
        list.addAll(App.getDBcApplication().getAllSendRepeatNoteData(userid, puid, 4,false) as ArrayList<UserFrendsTask>)
        list.addAll(App.getDBcApplication().getAllSendRepeatNoteData(userid, puid, 6,false) as ArrayList<UserFrendsTask>)

        if (list.size == 0) {
            tishi_tv.visibility = View.VISIBLE
            pull_refresh_scrollview.visibility = View.GONE
        } else {
            tishi_tv.visibility = View.GONE
            pull_refresh_scrollview.visibility = View.VISIBLE
        }
    }

    private fun setInit() {
        val imageUrl = URLConstants.图片 + pimage + "&imageType=2&imageSizeType=3"

        head_name.text = pname

        imageLoader.displayImage(imageUrl, head_img, options, animateFirstListener)
    }


    private fun loadData() {
        val httpUtils = HttpUtils(5000)
        val params = RequestParams()
        params.addBodyParameter("uid", userid)
        params.addBodyParameter("cpId", "")
        params.addBodyParameter("downTime",  "")
        params.addBodyParameter("titleId",  "")
        params.addBodyParameter("type",  "0")
        httpUtils.send(HttpRequest.HttpMethod.POST, URLConstants.任务下行, params, object : RequestCallBack<String>() {
            override fun onSuccess(responseInfo: ResponseInfo<String>) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    val gson = Gson()
                    val sixTaskBean = gson.fromJson(responseInfo.result, DownNewSixTaskBean::class.java)
                    if (sixTaskBean.status == 0) {
                        share.putString(applicationContext, ShareFile.USERFILE, ShareFile.DOWNTASKTIME, sixTaskBean.downTime.replace('T', ' '))
                        val listBeanList = sixTaskBean.list
                        if (listBeanList != null) {
                            listBeanList
                                    .filterNotNull()
                                    .forEach {
                                        if (it.ctype == 1) {
                                            App.getDBcApplication().insertSendRepeatNoteTableData(it.id, it.uid, it.ctype, it.ptype,
                                                    it.puId, it.pdeleState, it.repInStable, it.repType, it.cbeforTime,
                                                    it.cdisplayAlarm, it.cpostpone, it.cimportant, it.pIsEnd, it.cisEnd, it.styles,
                                                    it.cisDown, it.ccolorType,
                                                    it.uname, it.pname, it.titleImg,
                                                    it.content, it.cdate, it.ctime, it.repTypeParameter, it.cisAlarm,
                                                    it.calarmSound, it.calarmSoundDesc, it.createTime,
                                                    DateUtil.formatDateTime(Date()), it.titleId, it.remark, it.remark1, it.remark2,
                                                    it.remark3, it.remark4, it.remark5, it.remark6)
                                        }
                                    }
                            updateFrendTaskIsDown()
                        }
                        getData()
                        adapter.notifyDataSetChanged()
                    }
                } else {
                    Toast.makeText(this@NewFriendSendDataActivity, "网络异常", Toast.LENGTH_SHORT).show()
                }
                pull_refresh_scrollview.onRefreshComplete()
            }

            override fun onFailure(e: HttpException, s: String) {
                pull_refresh_scrollview.onRefreshComplete()
                Toast.makeText(this@NewFriendSendDataActivity, "网络异常", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun updateFrendTaskIsDown() {
        dowmTime = share.getString(applicationContext, ShareFile.USERFILE, ShareFile.DOWNTASKTIME, "2017-12-20 00:00:00")
        val request = object : StringRequest(Method.POST, URLConstants.接收方任务收到通知, Response.Listener { s -> val ss = s }, Response.ErrorListener { }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String> {
                val map = HashMap<String, String>()
                map.put("uid", userid)
                map.put("downTime", dowmTime)
                return map
            }
        }
        request.tag = "updateFrendTaskIsDown"
        request.retryPolicy = DefaultRetryPolicy(3000, 1, 1.0f)
        App.getHttpQueues().add(request)
    }

    /**
     * 图片加载第一次显示监听器
     *
     * @author Administrator
     */
    private class AnimateFirstDisplayListener : SimpleImageLoadingListener() {

        override fun onLoadingComplete(imageUri: String, view: View?,
                                       loadedImage: Bitmap?) {
            if (loadedImage != null) {
                val imageView = view as ImageView?
                // 是否第一次显示
                val firstDisplay = !displayedImages.contains(imageUri)
                if (firstDisplay) {
                    // 图片淡入效果
                    FadeInBitmapDisplayer.animate(imageView, 500)
                    displayedImages.add(imageUri)
                }
            }
        }

        companion object {

            internal val displayedImages: MutableList<String> = Collections.synchronizedList(LinkedList())
        }
    }

    inner class ChildAdapter : RecyclerView.Adapter<ChildAdapter.Holder>() {

        override fun getItemCount(): Int {
            return list.size
        }

        var swipeLinearLayouts = arrayListOf<SwipeLinearLayout>()
        override fun onBindViewHolder(holder: ChildAdapter.Holder, position: Int) {

            val params1 = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
            if (holder.adapterPosition == list.size - 1) {
                params1.setMargins(0, 0, 0, Utils.dipTopx(context, 60f))
            } else {
                params1.setMargins(0, 0, 0, 0)
            }
            holder.itemView.ll.layoutParams = params1

            if (holder.adapterPosition == 0) {
                holder.itemView.date_ll.visibility = View.VISIBLE
            } else if (list[holder.adapterPosition].repType == list[holder.adapterPosition - 1].repType) {
                holder.itemView.date_ll.visibility = View.GONE
            } else if (list[holder.adapterPosition].repType == 4 && list[holder.adapterPosition - 1].repType == 6) {
                holder.itemView.date_ll.visibility = View.GONE
            } else if (list[holder.adapterPosition].repType == 6 && list[holder.adapterPosition - 1].repType == 4) {
                holder.itemView.date_ll.visibility = View.GONE
            } else {
                holder.itemView.date_ll.visibility = View.VISIBLE
            }

            var clockTime = ""
            val colorState = ""
            val alarmClockTime = list[holder.adapterPosition].ctime
            val beforTime = list[holder.adapterPosition].cBeforTime
            var beforeStr = ""

            when (beforTime) {
                0 -> beforeStr = "0"
                5 -> beforeStr = "-5"
                15 -> beforeStr = "-15"
                30 -> beforeStr = "-30"
                60 -> beforeStr = "-1h"
                120 -> beforeStr = "-2h"
                1440 -> beforeStr = "-1d"
                2 * 1440 -> beforeStr = "-2d"
                7 * 1440 -> beforeStr = "-1w"
                else -> beforeStr = "0"
            }
            clockTime = if (beforeStr == "0") {
                ("  <font color='" + colorState + "' size='5px'>"
                        + alarmClockTime + "</font>")
            } else {
                ("  <font color='" + colorState + "' size='5px'>"
                        + alarmClockTime + "(" + beforeStr + ")" + "</font>")
            }
            val allday = ("<font color='" + colorState + "' size='5px'>"
                    + "全天" + "</font>")
            val strdate = list[holder.adapterPosition].repTypeParameter
                    .replace("[", "").replace("]", "").replace("\n\"", "").replace("\n", "")
                    .replace("\"", "")
            val weekStr: String
            holder.itemView.content_tv.text = list[holder.adapterPosition].content
            if (list[holder.adapterPosition].cIsDown == 0) {
                holder.itemView.pasue_tv.visibility = View.GONE
            }

            if (list[holder.adapterPosition].pDeleState == 1) {
                holder.itemView.pasue_tv.text = "已删除"
                holder.itemView.pasue_tv.visibility = View.VISIBLE
            }

            if (list[holder.adapterPosition].cPostpone == 1) {
                holder.itemView.shun_tv.visibility = View.VISIBLE
            } else {
                holder.itemView.shun_tv.visibility = View.GONE
            }

            if (list[holder.adapterPosition].remark2 == "1") {
                holder.itemView.stop_tv.text = "开启"
                holder.itemView.context_rl.background = resources.getDrawable(R.drawable.bg_rep_pause)
            } else {
                holder.itemView.stop_tv.text = "暂停"
                holder.itemView.context_rl.background = resources.getDrawable(R.drawable.bg_repeat_normal)
            }
            swipeLinearLayouts.add(holder.itemView.content_ll)
            holder.itemView.content_ll.setOnSwipeListener { thisSll, isHorizontal ->
                if (!isHorizontal) {
                    swipeLinearLayouts
                            .forEach { it.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK) }
                } else {
                    swipeLinearLayouts
                            .filter { it != thisSll }
                            .forEach {
                                //划开一个sll， 其他收缩
                                it.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK)
                            }
                }
            }
            holder.itemView.stop_tv.setOnClickListener {
                if (list[holder.adapterPosition].remark2 == "0") {
                    holder.itemView.context_rl.background = resources.getDrawable(R.drawable.bg_rep_pause)
                    list[holder.adapterPosition].remark2 = "1"
                    App.getDBcApplication().updateSendRepeatNotePause(list[holder.adapterPosition].id, "1")
                } else {
                    holder.itemView.context_rl.background = resources.getDrawable(R.drawable.bg_repeat_normal)
                    list[holder.adapterPosition].remark2 = "0"
                    App.getDBcApplication().updateSendRepeatNotePause(list[holder.adapterPosition].id, "0")
                }
                adapter.notifyItemChanged(holder.adapterPosition, 1)
                synData()
                holder.itemView.content_ll.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK)
            }

            holder.itemView.delete_tv.setOnClickListener {
                App.getDBcApplication().deleteSendRepeatNoteData(list[holder.adapterPosition].id)
                list.remove(list[holder.adapterPosition])
                adapter.notifyItemRemoved(holder.adapterPosition)
                adapter.notifyItemRangeChanged(holder.adapterPosition, list.size, 1)
                synData()
                holder.itemView.content_ll.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK)
            }
            holder.itemView.context_rl.setOnClickListener {
                dialogClickc(list[holder.adapterPosition], holder.adapterPosition)
                holder.itemView.content_ll.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK)
            }
            val displaying = list[holder.adapterPosition].cDisplayAlarm
            if (1 == displaying) {
                when {
                    1 == list[holder.adapterPosition].repType -> {
                        holder.itemView.riqi_tv.visibility = View.GONE
                        holder.itemView.nongli_tv.visibility = View.GONE
                        holder.itemView.date_tv.text = "每天"
                        holder.itemView.time_tv.text = Html.fromHtml(clockTime)
                    }
                    2 == list[holder.adapterPosition].repType -> {
                        holder.itemView.riqi_tv.visibility = View.VISIBLE
                        holder.itemView.nongli_tv.visibility = View.GONE
                        holder.itemView.date_tv.text = "每周"
                        weekStr = when (strdate) {
                            "1" -> "一"
                            "2" -> "二"
                            "3" -> "三"
                            "4" -> "四"
                            "5" -> "五"
                            "6" -> "六"
                            else -> "日"
                        }
                        holder.itemView.riqi_tv.text = "周" + weekStr
                        holder.itemView.time_tv.text = Html.fromHtml(clockTime)
                    }
                    3 == list[holder.adapterPosition].repType -> {
                        holder.itemView.riqi_tv.visibility = View.VISIBLE
                        holder.itemView.nongli_tv.visibility = View.GONE
                        holder.itemView.date_tv.text = "每月"
                        holder.itemView.riqi_tv.text = strdate + "日"
                        holder.itemView.time_tv.text = Html.fromHtml(clockTime)
                    }
                    4 == list[holder.adapterPosition].repType -> {
                        holder.itemView.riqi_tv.visibility = View.VISIBLE
                        holder.itemView.date_tv.text = "每年"
                        holder.itemView.nongli_tv.visibility = View.GONE
                        holder.itemView.riqi_tv.text = strdate
                        holder.itemView.time_tv.text = Html.fromHtml(clockTime)
                    }
                    6 == list[holder.adapterPosition].repType -> {
                        holder.itemView.riqi_tv.visibility = View.VISIBLE
                        holder.itemView.date_tv.text = "每年"
                        holder.itemView.nongli_tv.visibility = View.VISIBLE
                        holder.itemView.riqi_tv.text = strdate
                        holder.itemView.time_tv.text = Html.fromHtml(clockTime)
                    }
                    else -> {
                        holder.itemView.riqi_tv.visibility = View.GONE
                        holder.itemView.nongli_tv.visibility = View.GONE
                        holder.itemView.date_tv.text = "工作日"
                        holder.itemView.time_tv.text = Html.fromHtml(clockTime)
                    }
                }
            } else {
                when {
                    1 == list[holder.adapterPosition].repType -> {
                        holder.itemView.riqi_tv.visibility = View.GONE
                        holder.itemView.nongli_tv.visibility = View.GONE
                        holder.itemView.date_tv.text = "每天"
                        holder.itemView.time_tv.text = Html.fromHtml(allday)
                    }
                    2 == list[holder.adapterPosition].repType -> {
                        holder.itemView.riqi_tv.visibility = View.VISIBLE
                        holder.itemView.nongli_tv.visibility = View.GONE
                        holder.itemView.date_tv.text = "每周"
                        weekStr = when (strdate) {
                            "1" -> "一"
                            "2" -> "二"
                            "3" -> "三"
                            "4" -> "四"
                            "5" -> "五"
                            "6" -> "六"
                            else -> "日"
                        }
                        holder.itemView.riqi_tv.text = "周" + weekStr
                        holder.itemView.time_tv.text = Html.fromHtml(allday)
                    }
                    3 == list[holder.adapterPosition].repType -> {
                        holder.itemView.nongli_tv.visibility = View.GONE
                        holder.itemView.date_tv.text = "每月"
                        holder.itemView.riqi_tv.text = strdate + "日"
                        holder.itemView.time_tv.text = Html.fromHtml(allday)
                    }
                    4 == list[holder.adapterPosition].repType -> {
                        holder.itemView.nongli_tv.visibility = View.GONE
                        holder.itemView.date_tv.text = "每年"
                        holder.itemView.riqi_tv.text = strdate
                        holder.itemView.time_tv.text = Html.fromHtml(allday)
                    }
                    5 == list[holder.adapterPosition].repType -> {
                        holder.itemView.date_tv.text = "每年"
                        holder.itemView.nongli_tv.visibility = View.VISIBLE
                        holder.itemView.riqi_tv.text = strdate
                        holder.itemView.time_tv.text = Html.fromHtml(clockTime)
                    }
                    else -> {
                        holder.itemView.nongli_tv.visibility = View.GONE
                        holder.itemView.riqi_tv.visibility = View.GONE
                        holder.itemView.date_tv.text = "工作日"
                        holder.itemView.time_tv.text = Html.fromHtml(allday)
                    }
                }
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChildAdapter.Holder {
            val view = LayoutInflater.from(this@NewFriendSendDataActivity).inflate(R.layout.adapter_send_repeat_item, parent, false)
            return Holder(view)
        }


        inner class Holder(itemview: View) : RecyclerView.ViewHolder(itemview)

    }


    private fun addDaile() {
        val dialog = Dialog(context, R.style.dialog_translucent)
        val window = dialog.window
        val params = window!!.attributes// 获取LayoutParams
        window.setGravity(Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL)
        window.attributes = params// 设置生效

        val fac = LayoutInflater.from(context)
        val view = fac.inflate(R.layout.dialog_new_friend_send_repeat_add, null)
        dialog.setCanceledOnTouchOutside(true)
        dialog.setContentView(view)
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT
        params.width = windowManager.defaultDisplay.width
        dialog.show()


        val intent = Intent(this@NewFriendSendDataActivity, NewFriendSendRepeatNoteEditActivity::class.java)
        view.findViewById<TextView>(R.id.add_day).setOnClickListener {
            intent.putExtra("date", "每天")
            intent.putExtra("newadd", true)
            intent.putExtra("puid", puid)
            intent.putExtra("pname", pname)
            startActivityForResult(intent, 100)
            dialog.dismiss()
        }
        view.findViewById<TextView>(R.id.add_word_day).setOnClickListener {
            intent.putExtra("date", "工作日")
            intent.putExtra("newadd", true)
            intent.putExtra("puid", puid)
            intent.putExtra("pname", pname)
            startActivityForResult(intent, 100)
            dialog.dismiss()
        }
        view.findViewById<TextView>(R.id.add_week).setOnClickListener {
            intent.putExtra("date", "每周")
            intent.putExtra("puid", puid)
            intent.putExtra("pname", pname)
            intent.putExtra("newadd", true)
            startActivityForResult(intent, 100)
            dialog.dismiss()
        }
        view.findViewById<TextView>(R.id.add_month).setOnClickListener {
            intent.putExtra("date", "每月")
            intent.putExtra("newadd", true)
            intent.putExtra("puid", puid)
            intent.putExtra("pname", pname)
            startActivityForResult(intent, 100)
            dialog.dismiss()
        }
        view.findViewById<TextView>(R.id.add_year).setOnClickListener {
            intent.putExtra("date", "每年")
            intent.putExtra("puid", puid)
            intent.putExtra("pname", pname)
            intent.putExtra("newadd", true)
            startActivityForResult(intent, 100)
            dialog.dismiss()
        }
        view.findViewById<TextView>(R.id.cancel).setOnClickListener {
            dialog.dismiss()
        }


    }

    private fun dialogClickc(bean: UserFrendsTask, position: Int) {
        val dialog = Dialog(context, R.style.dialog_translucent)
        val window = dialog.window
        val params = window!!.attributes// 获取LayoutParams
        window.setGravity(Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL)
        window.attributes = params// 设置生效

        val fac = LayoutInflater.from(context)
        val view = fac.inflate(R.layout.dialog_calender_new_detail, null)

        dialog.setCanceledOnTouchOutside(true)
        dialog.setContentView(view)
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT
        params.width = windowManager.defaultDisplay.width - 30
        dialog.show()

        val viewList = java.util.ArrayList<View>()

        val myViewPager = view.findViewById(R.id.viewpager_detail) as MyViewPager

        val viewOne = LayoutInflater.from(context).inflate(R.layout.dialog_repeat_new_detail_item1, null)
        val viewTwo = LayoutInflater.from(context).inflate(R.layout.dialog_repeat_new_detail_item2, null)

        val bianjitv = viewOne.findViewById(R.id.bianji) as TextView
        val zant = viewOne.findViewById(R.id.zant) as TextView
        val copy = viewOne.findViewById(R.id.copy) as TextView
        val zhuanfa = viewOne.findViewById(R.id.zhuanfa_ll) as LinearLayout
        val importtv = viewOne.findViewById(R.id.important) as TextView
        importtv.visibility = View.GONE
        zhuanfa.visibility = View.VISIBLE

        if ("0" == bean.remark2) {
            zant.text = "暂停"
        } else {
            zant.text = "开启"
        }

        bianjitv.setOnClickListener{
            val intent = Intent(this@NewFriendSendDataActivity, NewFriendSendRepeatNoteEditActivity::class.java)
            intent.putExtra("newadd", false)
            intent.putExtra("puid", puid)
            intent.putExtra("pname", pname)
            intent.putExtra("repeatbean", bean)
            startActivity(intent)
            dialog.dismiss()
        }
        zhuanfa.setOnClickListener{
            val inten = Intent(context, SelectionFirendActivity::class.java)
            inten.putExtra("schSourceType", "100")
            inten.putExtra("schRemark1", "")
            inten.putExtra("updateState", "1")
            inten.putExtra("schID", "0")
            inten.putExtra("bean", bean)
            inten.putExtra("titleid", "")
            inten.putExtra("titles", "")
            inten.putExtra("remark6", "")
            inten.putExtra("remark5", "")
            startActivity(inten)
            dialog.dismiss()
        }
        copy.setOnClickListener{
            App.getDBcApplication().copySendRepeatNoteData(bean.id, userid, bean.titleId)
            dialog.dismiss()
            getData()
            synData()
            adapter.notifyItemRangeChanged(position, list.size, 1)
        }


        zant.setOnClickListener{
            if (bean.remark2 == "0") {
                bean.remark2 = "1"
                App.getDBcApplication().updateSendRepeatNotePause(bean.id, "1")
            } else {
                bean.remark2 = "0"
                App.getDBcApplication().updateSendRepeatNotePause(bean.id, "0")
            }
            synData()
            adapter.notifyItemChanged(position, 1)
            dialog.dismiss()
        }

        try {
            fileDescriptor = assets.openFd(bean.cAlarmSound + ".mp3")
            mediaPlayer.setDataSource(
                    fileDescriptor!!.fileDescriptor,
                    fileDescriptor!!.startOffset,
                    fileDescriptor!!.length)
            mediaPlayer.prepare()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        viewTwo.findViewById<TextView>(R.id.add_note).visibility = View.GONE

        viewTwo.findViewById<TextView>(R.id.shitinglings).setOnClickListener {
            if (mediaPlayer.isPlaying) {
                mediaPlayer.stop()
                mediaPlayer.reset()
                try {
                    val fileDescriptor = assets.openFd(bean.cAlarmSound + ".mp3")
                    mediaPlayer.setDataSource(
                            fileDescriptor.fileDescriptor,
                            fileDescriptor.startOffset,
                            fileDescriptor.length)
                    mediaPlayer.prepare()
                    mediaPlayer.start()
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            } else {
                mediaPlayer.start()
            }
        }

        viewTwo.findViewById<TextView>(R.id.delete).setOnClickListener {
            App.getDBcApplication().deleteSendRepeatNoteData(bean.id)
            list.remove(bean)
            adapter.notifyItemRemoved(position)
            adapter.notifyItemRangeChanged(position, list.size, 1)
            synData()
            dialog.dismiss()
        }

        viewList.add(viewOne)
        viewList.add(viewTwo)

        val viewAdapter = ViewAdapter(viewList)
        myViewPager.adapter = viewAdapter

        val yd1 = view.findViewById(R.id.yd1) as ImageView
        val yd2 = view.findViewById(R.id.yd2) as ImageView

        myViewPager.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                yd1.background = resources.getDrawable(R.drawable.calender_new_detail_yd1)
                yd2.background = resources.getDrawable(R.drawable.calender_new_detail_yd1)
                if (position == 0) {
                    yd1.background = resources.getDrawable(R.drawable.calender_new_detail_yd2)
                }
                if (position == 1) {
                    yd2.background = resources.getDrawable(R.drawable.calender_new_detail_yd2)
                }
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })

    }

    internal inner class ViewAdapter(private val viewList: List<View>) : PagerAdapter() {

        override fun getCount(): Int {
            return viewList.size
        }

        override fun isViewFromObject(view: View, `object`: Any): Boolean {
            return view === `object`
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            container.addView(viewList[position])
            return viewList[position]
        }
    }
    internal var mediaPlayer: MediaPlayer = MediaPlayer()
    internal var fileDescriptor: AssetFileDescriptor? = null

    private val progressUtil = ProgressUtil()
    private fun synData() {
        progressUtil.ShowProgress(context, true, true, "同步中...")
        try {
            val bean1 = App.getDBcApplication().getAllSendRepeatNoteData(userid, puid, -1, true)
            val beans = App.getDBcApplication().getAllSendRepeatNoteDetailData(userid, puid, true)
            val data = JSONObject()
            val data1 = JSONObject()
            val array = JSONArray()
            val array1 = JSONArray()

            for (bean in bean1) {
                val task = JSONObject()

                task.put("id", bean.id)
                task.put("uid", bean.uId)
                task.put("ctype", bean.ctype)
                task.put("uname", bean.uname)
                task.put("pname", bean.pname)
                task.put("ptype", bean.ptype)
                task.put("titleImg", bean.titleImg)
                task.put("puId", bean.puId)
                task.put("pdeleState", bean.pDeleState)
                task.put("content", bean.content)
                task.put("cdate", bean.cdate)
                task.put("ctime", bean.ctime)
                task.put("repInStable", bean.repInSTable)
                task.put("repType", bean.repType)
                task.put("repTypeParameter", bean.repTypeParameter.replace("\"",""))
                task.put("cisAlarm", bean.cIsAlarm)
                task.put("cbeforTime", bean.cBeforTime)
                task.put("calarmSound", bean.cAlarmSound)
                task.put("calarmSoundDesc", bean.cAlarmSoundDesc)
                task.put("cdisplayAlarm", bean.cDisplayAlarm)
                task.put("cpostpone", bean.cPostpone)
                task.put("cimportant", bean.cImportant)
                task.put("cisEnd", bean.cIsEnd)
                task.put("pIsEnd", bean.pIsEnd)
                task.put("styles", bean.styles)
                task.put("cisDown", bean.cIsDown)
                task.put("ccolorType", bean.cColorType)
                task.put("createTime", bean.createTime)
                task.put("changTime", bean.changTime)
                task.put("titleId", bean.titleId)
                task.put("remark", bean.remark)
                task.put("remark1", bean.remark1)
                task.put("remark2", bean.remark2)
                task.put("remark3", bean.remark3)
                task.put("remark4", bean.remark4)
                task.put("remark5", bean.remark5)
                task.put("remark6", bean.remark6)
                task.put("updateState", App.getDBcApplication().getOneSendRepeatNoteUpdatestate(userid, puid, bean.titleId, true))
                array.put(task)
            }


            data.put("timetable", array)

            for (be in beans) {
                val tasks = JSONObject()
                tasks.put("id", be.id)
                tasks.put("uid", be.uId)
                tasks.put("puId", be.puId)
                tasks.put("ctype", be.ctype)
                tasks.put("titleId", be.titleId)
                tasks.put("titles", be.titles)
                tasks.put("contents", be.contents)
                tasks.put("changeTime", be.changeTime)
                tasks.put("orderId", be.orderId)
                tasks.put("imgPath", be.imgPath)
                tasks.put("imgUrl", be.imgUrl)
                tasks.put("createTime", be.createTime)
                tasks.put("ltype", be.lType)
                tasks.put("style", be.style)
                tasks.put("endstate", be.endstate)
                tasks.put("nums", be.nums)
                tasks.put("cpath", be.cpath)
                tasks.put("curl", be.curl)
                tasks.put("shareUrl", be.shareUrl)
                tasks.put("sdesc", be.sdesc)
                tasks.put("localIds", be.localIds)
                tasks.put("remark", be.remark)
                tasks.put("remark1", be.remark1)
                tasks.put("remark2", be.remark2)
                tasks.put("remark3", be.remark3)
                tasks.put("remark4", be.remark4)
                tasks.put("remark5", be.remark5)
                tasks.put("remark6", be.remark6)
                tasks.put("remark7", be.remark7)
                tasks.put("remark8", be.remark8)
                tasks.put("updateState", App.getDBcApplication().getOneSendRepeatNoteDetailUpdatestate(userid, puid, be.titleId, be.id, true))
                array1.put(tasks)
            }

            data1.put("timetable", array1)

            val params = RequestParams()
            params.addBodyParameter("data", data.toString())
            params.addBodyParameter("data1", data1.toString())
            HttpUtils(5000).send(HttpRequest.HttpMethod.POST, URLConstants.发起方任务同步, params, object : RequestCallBack<String>() {
                override fun onSuccess(responseInfo: ResponseInfo<String>) {
                    if (!TextUtils.isEmpty(responseInfo.result)) {
                        try {
                            val gson = Gson()
                            val synBean = gson.fromJson(responseInfo.result, TaskSynBean::class.java)
                            if (synBean.status == 0) {
                                val listBeanList = synBean.list
                                if (listBeanList != null) {
                                    for (tDeListBean in listBeanList) {
                                        when {
                                            tDeListBean.dataState == 1 -> //新增
                                                when {
                                                    tDeListBean.state == 0 -> {//成功
                                                        //修改id和状态值
                                                        App.getDBcApplication().updateSendRepeatNoteTitleId(tDeListBean.id, tDeListBean.newId, userid)
                                                        App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.newId, userid, 0, true)
                                                    }
                                                    tDeListBean.state == 1 -> //失败  可以不操作,但是避免意外
                                                        //更改状态为1
                                                        App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userid, 1, true)
                                                    tDeListBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userid, -1, true)
                                                }
                                            tDeListBean.dataState == 2 -> //修改
                                                when {
                                                    tDeListBean.state == 0 -> //成功
                                                        //修改该id状态值
                                                        App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userid, 0, true)
                                                    tDeListBean.state == 1 -> //失败
                                                        //更改状态为2
                                                        App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userid, 2, true)
                                                    tDeListBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userid, -1, true)
                                                }
                                            tDeListBean.dataState == 3 -> //删除
                                                when {
                                                    tDeListBean.state == 0 -> //成功
                                                        //删除该id的清单
                                                        App.getDBcApplication().deleteSendRepeatNoteData1(tDeListBean.id)
                                                    tDeListBean.state == 1 -> //失败
                                                        //更改状态为3
                                                        App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userid, 3, true)
                                                    tDeListBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userid, -1, true)
                                                }
                                        }
                                    }
                                }

                                val listBeans = synBean.list2
                                if (listBeans != null) {
                                    for (listBean in listBeans) {
                                        when {
                                            listBean.dataState == 1 -> //新增
                                                when {
                                                    listBean.state == 0 -> {//成功
                                                        //修改id和状态值
                                                        App.getDBcApplication().updateSendRepeatNoteDetailId(listBean.id, listBean.newId, userid)
                                                        App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.newId, userid, 0)
                                                    }
                                                    listBean.state == 1 -> //失败  可以不操作,但是避免意外
                                                        //更改状态为1
                                                        App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userid, 1)
                                                    listBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userid, -1)
                                                }
                                            listBean.dataState == 2 -> //修改
                                                when {
                                                    listBean.state == 0 -> //成功
                                                        //修改该id状态值
                                                        App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userid, 0)
                                                    listBean.state == 1 -> //失败
                                                        //更改状态为2
                                                        App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userid, 2)
                                                    listBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userid, -1)
                                                }
                                            listBean.dataState == 3 -> //删除
                                                when {
                                                    listBean.state == 0 -> //成功
                                                        //删除该id的清单
                                                        App.getDBcApplication().deleteSendRepeatNoteDetails(listBean.id, userid)
                                                    listBean.state == 1 -> //失败
                                                        //更改状态为3
                                                        App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userid, 3)
                                                    listBean.state == 2 -> //异常
                                                        App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userid, -1)
                                                }
                                        }
                                    }
                                }
                            }
                        } catch (e: JsonSyntaxException) {
                            e.printStackTrace()
                        }

                    }
                    progressUtil.dismiss()
                }

                override fun onFailure(e: HttpException, s: String) {
                    Log.e("TAG", s)
                    progressUtil.dismiss()
                }
            })

        } catch (e: JSONException) {
            e.printStackTrace()
        }

    }

}